<template>
  <el-dialog v-model="dialogVisible" :title="formType == 'create' ? '新增土地基础信息' : '编辑土地基础信息'" width="1200px" append-to-body>
    <div class="kuaicenter">
      <div class="kuai"></div>
      <h2>年度月度经营信息</h2>
    </div>
    <el-form ref="informationFormRef" v-loading="formLoading" :disabled="disabled" :model="formData" :rules="formRules" label-width="100px">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="名 称" prop="form.lanName">
            <el-date-picker v-model="formData.form.year" clearable type="year" value-format="YYYY" placeholder="年份" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="位置" prop="form.parcelCode">
            <el-input v-model="formData.form.parcelCode" placeholder="请输入位置" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产能" prop="form.plotLocation">
            <el-input v-model="formData.form.plotLocation" placeholder="请输入产能" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="投产日期" prop="form.commencementDate">
            <el-date-picker v-model="formData.form.commencementDate" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择投产日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状 态" prop="form.lanName">
            <el-date-picker v-model="formData.form.year" clearable type="month" value-format="MM" placeholder="状 态" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属单位" prop="form.parcelCode">
            <el-input v-model="formData.form.parcelCode" placeholder="请输入所属单位" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联&nbsp;&nbsp;系&nbsp;&nbsp;人" prop="form.plotLocation">
            <el-input v-model="formData.form.plotLocation" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系方式" prop="form.commencementDate">
            <el-input v-model="formData.form.plotLocation" placeholder="请输入联系方式" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="实景图片" prop="form.realPictures">
            <image-upload v-model="formData.form.realPictures" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="kuaicenter">
        <div class="kuai"></div>
        <h2>经营信息</h2>
      </div>
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="年 份" prop="form.lanName">
            <el-date-picker v-model="formData.form.year" clearable type="year" value-format="YYYY" placeholder="年份" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="月 份" prop="form.lanName">
            <el-date-picker v-model="formData.form.year" clearable type="month" value-format="MM" placeholder="月份" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="统计日期" prop="form.commencementDate">
            <el-date-picker v-model="formData.form.commencementDate" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择统计日期">
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="月供应量" prop="rentReceivable">
            <el-input v-model="formData.form.plotLocation" class="cell-input" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="供应均价" prop="rentReceivable">
            <el-input v-model="formData.form.plotLocation" class="cell-input" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="月营业额" prop="rentReceivable">
            <el-input v-model="formData.form.plotLocation" class="cell-input" />
          </el-form-item>
        </el-col>
      </el-row>
      <div>
        <div v-if="formData.rentCollectionPlan.length === 0" style="text-align: right">
          <el-button :loading="buttonLoading" type="primary" @click="handlePush">新增行</el-button>
        </div>
        <H2 class="mb-5" style="text-align: center; font-weight: bold">经营信息</H2>
        <el-table :data="formData.rentCollectionPlan" style="width: 100%">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="dueDate" label="供应项目">
            <template #default="scope">
              <el-input v-model="scope.row.rentReceivable" class="cell-input" />
            </template>
          </el-table-column>
          <el-table-column prop="rentReceivable" label="供应量（m³）">
            <template #default="scope">
              <el-input v-model="scope.row.rentReceivable" class="cell-input" />
            </template>
          </el-table-column>
          <el-table-column prop="rentReceivable" label="供应均价(元/m³)">
            <template #default="scope">
              <el-input v-model="scope.row.rentReceivable" class="cell-input" />
            </template>
          </el-table-column>
          <el-table-column prop="rentReceivable" label="营业额（元）">
            <template #default="scope">
              <el-input v-model="scope.row.rentReceivable" class="cell-input" />
            </template>
          </el-table-column>
          <el-table-column width="110" label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <div v-if="disabled">-</div>
              <div v-else>
                <el-button link type="primary" @click="handlePush"> 新增 </el-button>
                <el-button link type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>
    <template v-if="!disabled" #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" name="SystemRoleForm" setup>
import {
  getInformation,
  addInformation,
  updateInformation,
  addRentCollectionPlan,
  rentCollectionPlanList,
  updateRentCollectionPlan,
  delrentCollectionPlan
} from '@/api/zichanguanli/information';
import { getLeaseInformation, addLeaseInformation, updateLeaseInformation } from '@/api/zichanguanli/leaseInformation';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { land_ease_status, land_use, land_developmen_status, land_collateral_status, land_frequency_of_rent_payments } = toRefs<any>(
  proxy?.useDict('land_ease_status', 'land_use', 'land_developmen_status', 'land_collateral_status', 'land_frequency_of_rent_payments')
);

const disabled: any = ref(false); // 表单是否禁用
const buttonLoading = ref(false); // 按钮的 loading
const dialogVisible = ref(false); // 弹窗的是否展示
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(''); // 表单的类型：create - 新增；update - 修改

const formData: any = ref({
  form: {
    id: undefined,
    lanName: undefined,
    parcelCode: undefined,
    plotLocation: undefined,
    landArea: undefined,
    transferee: undefined,
    landuse: undefined,
    leaseStatus: undefined,
    collateralStatus: undefined,
    developmenStatus: undefined,
    projectName: undefined,
    commencementDate: undefined,
    completionDate: undefined,
    remarks: undefined,
    estimation: undefined,
    attachment: undefined,
    realPictures: undefined
  },
  initLeaseForm: {
    id: undefined,
    lessee: undefined,
    frequencyOfRentPayments: undefined,
    rents: undefined,
    associates: undefined,
    contactInformation: undefined,
    leaseTerm: undefined,
    startTime: undefined,
    endTime: undefined
  },
  rentCollectionPlan: []
});
const formRules = reactive({
  'form.lanName': [{ required: true, message: '土地名称不能为空', trigger: 'blur' }],
  'form.parcelCode': [{ required: true, message: '宗地编号不能为空', trigger: 'blur' }],
  'form.plotLocation': [{ required: true, message: '地块位置不能为空', trigger: 'blur' }],
  'form.landArea': [{ required: true, message: '土地面积不能为空', trigger: 'blur' }],
  'form.transferee': [{ required: true, message: '受让单位不能为空', trigger: 'blur' }],
  'form.leaseStatus': [{ required: true, message: '租赁状态不能为空', trigger: 'change' }],
  'initLeaseForm.contactInformation': [{  required: true, message: '请填写正确的手机号码', trigger: 'change' }]
});
const informationFormRef = ref(); // 表单 Ref

const handlePush = () => {
  formData.value.rentCollectionPlan.push({
    id: undefined,
    dueDate: undefined,
    rentReceivable: undefined,
    collect: undefined,
    paidInTime: undefined
  });
};

const handleDelete = async (index: number, row: any) => {
  if (row.id) {
    await delrentCollectionPlan(row.id);
    formData.value.rentCollectionPlan.splice(index, 1);
  } else {
    formData.value.rentCollectionPlan.splice(index, 1);
  }
};

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true;
  formType.value = type;
  disabled.value = false;
  resetForm();
  // 修改时，设置数据
  if (type === 'detail') {
    disabled.value = true;
  }
  if (id) {
    formLoading.value = true;
    try {
      const res = await getInformation(id);
      formData.value.form = { ...res.data };
      const resLandLease = await getLeaseInformation(id);
      formData.value.initLeaseForm = { ...resLandLease.data };
      const rentCollectionList = await rentCollectionPlanList({
        pageSize: 1000,
        pageNum: 1,
        landInfoId: id
      });
      formData.value.rentCollectionPlan = rentCollectionList.rows || [];
      console.log('?? ~ open ~ rentCollectionList:', rentCollectionList);
    } finally {
      formLoading.value = false;
    }
  }
};

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    form: {
      id: undefined,
      lanName: undefined,
      parcelCode: undefined,
      plotLocation: undefined,
      landArea: undefined,
      transferee: undefined,
      landuse: undefined,
      leaseStatus: undefined,
      collateralStatus: undefined,
      developmenStatus: undefined,
      projectName: undefined,
      commencementDate: undefined,
      completionDate: undefined,
      remarks: undefined,
      estimation: undefined,
      attachment: undefined,
      realPictures: undefined
    },
    initLeaseForm: {
      landInfoId: undefined,
      lessee: undefined,
      frequencyOfRentPayments: undefined,
      rents: undefined,
      associates: undefined,
      contactInformation: undefined,
      leaseTerm: undefined,
      startTime: undefined,
      endTime: undefined
    },
    rentCollectionPlan: []
  };
  informationFormRef.value?.resetFields();
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  const valid = await informationFormRef.value.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;
  try {
    let type = '';
    if (formType.value === 'create') {
      type = 'create';
      const res = await addInformation(formData.value.form);
      if (Object.keys(formData.value.initLeaseForm).length !== 0) {
        formData.value.initLeaseForm.landInfoId = res.data;
        await addLeaseInformation(formData.value.initLeaseForm);
      }
      if (formData.value.rentCollectionPlan.length !== 0) {
        formData.value.rentCollectionPlan.map(async (item: any) => {
          item.landInfoId = res.data;
          await addRentCollectionPlan(item);
        });
      }
    } else {
      type = 'update';
      await updateInformation(formData.value.form);
      if (formData.value.initLeaseForm.id) {
        await updateLeaseInformation(formData.value.initLeaseForm);
      } else {
        formData.value.initLeaseForm.landInfoId = formData.value.form.id;
        await addLeaseInformation(formData.value.initLeaseForm);
      }
      if (formData.value.rentCollectionPlan.length !== 0) {
        formData.value.rentCollectionPlan.map(async (item: any) => {
          if (item.landInfoId) {
            await updateRentCollectionPlan(item);
          } else {
            item.landInfoId = formData.value.form.id;
            await addRentCollectionPlan(item);
          }
        });
      }
    }
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit('success', type);
  } finally {
    formLoading.value = false;
  }
};
</script>
